package com.ruralflow.population.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruralflow.common.config.RuoYiConfig;
import com.ruralflow.common.utils.DateUtils;
import com.ruralflow.common.utils.SecurityUtils;
import com.ruralflow.common.utils.SequenceUtils;
import com.ruralflow.common.utils.file.FileUploadUtils;
import com.ruralflow.population.domain.vo.PopulationRespVO;
import com.ruralflow.system.service.ITess4jService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruralflow.population.mapper.PopulationMapper;
import com.ruralflow.population.domain.Population;
import com.ruralflow.population.service.IPopulationService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 流动人口信息Service业务层处理
 * 
 * @author ruralflow
 * @date 2025-02-15
 */
@Service
@Slf4j
public class PopulationServiceImpl implements IPopulationService 
{
    @Autowired
    private PopulationMapper populationMapper;

    @Autowired
    private SequenceUtils sequenceUtils;

    @Autowired
    private ITess4jService tess4jService;

    /**
     * 查询流动人口信息
     * 
     * @param populationId 流动人口信息主键
     * @return 流动人口信息
     */
    @Override
    public Population selectPopulationByPopulationId(Long populationId)
    {
        return populationMapper.selectPopulationByPopulationId(populationId);
    }

    /**
     * 查询流动人口信息列表
     * 
     * @param population 流动人口信息
     * @return 流动人口信息
     */
    @Override
    public List<Population> selectPopulationList(Population population)
    {
        return populationMapper.selectPopulationList(population);
    }

    /**
     * 新增流动人口信息
     * 
     * @param population 流动人口信息
     * @return 结果
     */
    @Override
    public int insertPopulation(Population population)
    {
        population.setCreateTime(DateUtils.getNowDate());
        population.setCreateBy(SecurityUtils.getUsername());
        population.setPopulationCode(getNo());
        return populationMapper.insertPopulation(population);
    }

    /**
     * 修改流动人口信息
     * 
     * @param population 流动人口信息
     * @return 结果
     */
    @Override
    public int updatePopulation(Population population)
    {
        population.setUpdateTime(DateUtils.getNowDate());
        population.setUpdateBy(SecurityUtils.getUsername());
        return populationMapper.updatePopulation(population);
    }

    /**
     * 批量删除流动人口信息
     * 
     * @param populationIds 需要删除的流动人口信息主键
     * @return 结果
     */
    @Override
    public int deletePopulationByPopulationIds(Long[] populationIds)
    {
        String updateBy = SecurityUtils.getUsername();
        return populationMapper.deletePopulationByPopulationIds(populationIds, updateBy);
    }

    /**
     * 删除流动人口信息信息
     * 
     * @param populationId 流动人口信息主键
     * @return 结果
     */
    @Override
    public int deletePopulationByPopulationId(Long populationId)
    {
        String updateBy = SecurityUtils.getUsername();
        return populationMapper.deletePopulationByPopulationId(populationId, updateBy);
    }

    @Override
    public Integer selectCountPopulation() {
        return populationMapper.selectCountPopulation();
    }

    /**
     * OCR识别流动人口信息
     *
     * @param multipartFile 图片文件
     * @return 流动人口信息
     */
    @Override
    public PopulationRespVO OCRPopulation(MultipartFile multipartFile) {
        PopulationRespVO populationRespVO = new PopulationRespVO();

        // 先识别，后期如果想加校验也可以（比如信息识别失败就不用保存文件了）
        Population population = new Population();
        String result = tess4jService.imageToText(multipartFile);
        log.info("识别结果：{}", result);
        // 构造流动人口信息
        if (result != null) {
            population = constructPopulation(result);
            BeanUtils.copyProperties(population, populationRespVO);
        }

        try {
            // 保存文件
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, multipartFile);
            populationRespVO.setFileName(fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return populationRespVO;
    }

    /*
     * 构造流动人口信息
     */
    private Population constructPopulation(String result) {
        Population population = new Population();
        // 定义正则表达式
        String nameRegex = "姓名:(.*?)[。]"; // 匹配 "姓名：" 和 "。" 之间的内容
        String ageRegex = "年龄:(\\d+)";
        String telephoneRegex = "联系方式:(\\d+)";   // 匹配 "电话：" 后面的数字
        String idCardRegex = "身份证:(\\d+)";

        // 提取姓名
        Pattern namePattern = Pattern.compile(nameRegex);
        Matcher nameMatcher = namePattern.matcher(result);
        String name = nameMatcher.find() ? nameMatcher.group(1) : null;
        population.setPopulationName(name);

        // 提取年龄
        Pattern agePattern = Pattern.compile(ageRegex);
        Matcher ageMatcher = agePattern.matcher(result);
        if (ageMatcher.find()) {
            String ageStr = ageMatcher.group(1);
            population.setPopulationAge(Long.parseLong(ageStr));
        }

        // 提取电话
        Pattern telephonePattern = Pattern.compile(telephoneRegex);
        Matcher telephoneMatcher = telephonePattern.matcher(result);
        String telephone = telephoneMatcher.find() ? telephoneMatcher.group(1) : null;
        population.setPopulationPhone(telephone);

        // 提取身份证
        Pattern idCardPattern = Pattern.compile(idCardRegex);
        Matcher idCardMatcher = idCardPattern.matcher(result);
        String idCard = idCardMatcher.find() ? idCardMatcher.group(1) : null;
        population.setPopulationIdCard(idCard);

        log.info("识别的population:{}", population);
        return population;
    }

    /**
     * 生成流动人口信息登记编码
     *
     * @return 流动人口信息登记编码
     */
    private String getNo() {
        // 获取用户id补0到五位
        Long userId = SecurityUtils.getUserId();
        String userIdStr = String.format("%05d", userId); // 补零到5位
        return sequenceUtils.createSequenceNumber("POT" + userIdStr);
    }
}
